let socketTask = null; // websocket对象
let heartbeatInterval = null; // 心跳定时器
let againTimer = null; // 重连定时器
let isSocketClose = false; // 是否关闭socket
// 连接回调
let onSucFn = null;
let onErrFn = null;
let onMsgFn = null;

const socket = (onErrorEvent, onErrorSucceed, onMessageFun) => {
	onErrFn = onErrorEvent;
	onSucFn = onErrorSucceed;
	onMsgFn = onMessageFun;
	isSocketClose = false;
	//判断是否有websocet对象，有的话清空
	if (socketTask) {
		socketTask.close();
		socketTask = null;
		clearInterval(heartbeatInterval);
	}
	// 连接socke
	socketTask = uni.connectSocket({
		url: 'wss://saas.hansifit.com/JbvZhE?',
		header: {
			'Authorization': uni.getStorageSync("token") && `Bearer ${uni.getStorageSync("token")}`
		},
		success() {
			clearInterval(againTimer) //断线重连定时器
		},
		fail: (err) => {
			console.log("报错", err);
		}
	})
	// 连接开启执行心跳包发送
	socketTask.onOpen((res) => {
		heartbeatInterval && clearInterval(heartbeatInterval);
		heartbeatInterval = setInterval(() => {
			sendMsg(JSON.stringify({
				'event': 'ping',
				'sign':  uni.getStorageSync("deviceId") || '',
				'data': {}
			}))
		}, 1000)
		onErrorSucceed()
	})
	// 接收到数据返回
	socketTask.onMessage((res) => {
		try {
			const data = JSON.parse(res.data);
			data.event != "pong" && onMsgFn(data)
		} catch (e) {
			console.error('WebSocket消息解析错误:', e);
		}
	})
	// 监听连接失败，不是人为关闭进行重连
	socketTask.onError((err) => {
		clearInterval(heartbeatInterval)
		!isSocketClose && reconnect(onErrFn, onSucFn)
	})
	// 监听连接关闭，不是人为关闭进行重连
	socketTask.onClose((e) => {
		clearInterval(heartbeatInterval)
		!isSocketClose && reconnect(onErrFn, onSucFn)
	})
}

//向后端发送命令
const sendMsg = (data) => { 
	try {
		socketTask.send({ data })
	} catch (e) {
		if (isSocketClose) {
			return
		} else {
			reconnect()
		}
	}
}

// 重新连接
const reconnect = () => {
	clearInterval(againTimer)
	clearInterval(heartbeatInterval)
	socketTask && socketTask.close();
	socketTask = null;
	onErrFn({
		isShow: true,
		messge: 'ws服务正在重连...'
	})
	againTimer = setInterval(() => {
		socket(onErrFn, onSucFn, onMsgFn)
	}, 1000 * 5)
}

// 关闭连接
const stop = callBack => {
	callBack && callBack();
	isSocketClose = true
	clearInterval(heartbeatInterval)
	clearInterval(againTimer)
	socketTask.close();
	socketTask = null;
}

export const ws = {
	socket,
	stop,
	sendMsg
}